<template>
  <view>
    <u-tabbar
      :active="userStore.activeTab"
      :fixed="true"
      :placeholder="true"
      :safeAreaInsetBottom="true"
    >
      <u-tabbar-item
        v-for="(item, index) in tabbarItems"
        :key="index"
        :icon="getTabbarIcon(item, index)"
        :text="item.text"
        @click="handleTabbarItemClick(item, index)"
      ></u-tabbar-item>
    </u-tabbar>
  </view>
</template>

<script setup>
//引入pinia仓库
import useUserStore from "@/store/user.js";
const userStore = useUserStore();

const tabbarItems = [
  {
    pagePath: "/pages/index/index",
    text: "首页",
    iconPath: "/static/tab_icons/home.png",
    selectedIconPath: "/static/tab_icons/home-active.png",
  },
  {
    pagePath: "/pages/scan/scan",
    text: "扫码",
    iconPath: "/static/tab_icons/scan.png",
    selectedIconPath: "/static/tab_icons/scan-active.png",
  },
  {
    pagePath: "/pages/order/order",
    text: "订单",
    iconPath: "/static/tab_icons/my.png",
    selectedIconPath: "/static/tab_icons/my-active.png",
  },
  {
    pagePath: "/pages/my/my",
    text: "我的",
    iconPath: "/static/tab_icons/my.png",
    selectedIconPath: "/static/tab_icons/my-active.png",
  },
  // {
  //   pagePath: "/pages/test/test",
  //   text: "测试",
  //   iconPath: "/static/tab_icons/my.png",
  //   selectedIconPath: "/static/tab_icons/my-active.png",
  // },
];
//点击tabbar按钮
const handleTabbarItemClick = (item, index) => {
  if (userStore.activeTab !== index) {
    //如果点击的是扫描按钮
    if (index === 1) {
      uni.scanCode({
        success(res) {
          const scanUrl = res.result;
          const regExp = /id=(\d+)/;
          const matchResult = scanUrl.match(regExp);
          let id = "";
          if (matchResult) {
            id = matchResult[1];
          }
          console.log("matchResylt:", matchResult);

          // return;
          uni.navigateTo({
            url: "/pages/pile/pile?id=" + id,
          });
        },
      });
    } else {
      userStore.setActive(index);
      const path = item.pagePath;
      if (path === "/pages/index/index") {
        // fetchUserRoleInfo();
      }
      uni.switchTab({
        url: path,
      });
    }
  }
};

//图标的切换
const getTabbarIcon = (item, index) => {
  return userStore.activeTab === index ? item.selectedIconPath : item.iconPath;
};
</script>
